<template>
  <div class="menu-management">
    <!-- 搜索表单 -->
    <div class="search-form">
      <div class="form-row">
        <div class="form-item-inline">
          <label>菜单名称</label>
                     <el-input
             v-model="searchForm.menuName"
             placeholder="请输入菜单名称"
             clearable
           />
        </div>
        <div class="form-item-inline">
          <label>菜单类型</label>
          <el-select v-model="searchForm.type" placeholder="选择类型" clearable>
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </div>
        <div class="form-item-inline">
          <label>状态</label>
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </div>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh" class="reset-btn">重置</el-button>
        </div>
      </div>
    </div>

    <div style="margin-bottom: 20px;">
      <el-button type="success" @click="handleAdd" :icon="Plus" class="add-btn">新增菜单</el-button>
    </div>

    <!-- 菜单列表容器 -->
    <div class="menu-list-container">
      <!-- 菜单列表滚动容器 -->
      <div class="list-scroll-container">
        <!-- 表头 -->
        <div class="list-header">
          <div class="header-item name-col">菜单名称</div>
          <div class="header-item path-col">路径</div>
          <div class="header-item type-col">类型</div>
          <div class="header-item sort-col">排序</div>
          <div class="header-item status-col">状态</div>
          <div class="header-item action-col">操作</div>
        </div>

        <div class="list-content" v-if="filteredData.length > 0">
          <div
            v-for="(menu, index) in filteredData"
            :key="menu.id"
            class="list-item"
          >
            <div class="list-row">
              <div class="name-col">
                <div class="name-content">
                  <el-icon :size="20" color="#667eea">
                    <Menu />
                  </el-icon>
                                     <span class="name">{{ menu.name }}</span>
                </div>
              </div>
              <div class="path-col">
                <span>{{ menu.path }}</span>
              </div>
              <div class="type-col">
                <el-tag type="primary" size="small">
                  菜单
                </el-tag>
              </div>
              <div class="sort-col">
                <span>{{ menu.meta?.order || 0 }}</span>
              </div>
              <div class="status-col">
                <el-tag :type="menu.meta?.requires_auth ? 'success' : 'danger'" size="small">
                  {{ menu.meta?.requires_auth ? '需要认证' : '无需认证' }}
                </el-tag>
              </div>
              <div class="action-col">
                <div class="action-buttons">
                  <el-button type="primary" size="small" plain @click="handleEdit(menu)" style="color: #a685ff; border-color: #a685ff; background-color: #f3f0ff;">编辑</el-button>
                  <el-button type="danger" size="small" plain @click="handleDelete(menu)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无菜单数据" />
        </div>
      </div>
    </div>



    <!-- 菜单弹窗组件 -->
    <MenuDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      :menu-tree="menuTree"
      @submit="handleDialogSubmit"
      @cancel="resetForm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Menu } from '@element-plus/icons-vue'
import MenuDialog from './components/MenuDialog.vue'
import {
  addMenu, deleteMenu,
  getMenuList, getMenuTree,
  type MenuItem, type CreateMenuRequest,
  updateMenu
} from "@/api/sys/menu.api.ts";

// 搜索表单
const searchForm = ref({
  menuName: '',
  type: '',
  status: ''
})



// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<MenuItem>>({})

// 菜单数据
const menuData = ref<MenuItem[]>([])
const menuTree = ref<MenuItem[]>([])

// 初始化数据
onMounted(async () => {
  try {
    // 实际项目中应该调用API
    const result = await getMenuList()
    menuData.value = result
    menuTree.value = result // 直接使用菜单列表作为树形数据
  } catch (error) {
    console.error('获取菜单数据失败:', error)
    ElMessage.error('获取菜单数据失败')
  }
})

// 过滤后的数据
const filteredData = computed(() => {
  return menuData.value.filter(menu => {
    const nameMatch = !searchForm.value.menuName ||
      menu.name.toLowerCase().includes(searchForm.value.menuName.toLowerCase())
    const typeMatch = !searchForm.value.type || true // 所有都是菜单类型
    const statusMatch = !searchForm.value.status || 
      (searchForm.value.status === 'active' ? menu.meta?.requires_auth : !menu.meta?.requires_auth)

    return nameMatch && typeMatch && statusMatch
  })
})



// 获取菜单类型标签类型
const getTypeTagType = (type: string) => {
  return type === 'menu' ? 'primary' : 'warning'
}

// 获取菜单类型标签文本
const getTypeLabel = (type: string) => {
  return type === 'menu' ? '菜单' : '按钮'
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  return status === 'active' ? 'success' : 'danger'
}

// 搜索
const handleSearch = () => {
  // 搜索功能保持不变
}

// 重置
const handleReset = () => {
  searchForm.value = {
    menuName: '',
    type: '',
    status: ''
  }
}

// 新增菜单
const handleAdd = () => {
  dialogTitle.value = '新增菜单'
  formData.value = {
    name: '',
    path: '',
    component: '',
    parent_id: '',
    meta: {
      roles: '',
      requires_auth: true,
      icon: '',
      locale: '',
      hideIn_menu: false,
      hide_childrenIn_menu: false,
      active_menu: '',
      order: 0,
      no_affix: false,
      ignore_cache: false,
      property1: '',
      property2: ''
    }
  }
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (menu: MenuItem) => {
  dialogTitle.value = '编辑菜单'
  formData.value = { ...menu }
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = async (menu: MenuItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${menu.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteMenu(menu.id)
    ElMessage.success('删除成功')
    
    // 重新获取数据
    const result = await getMenuList()
    menuData.value = result
    menuTree.value = result
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 弹窗提交
const handleDialogSubmit = async (data: CreateMenuRequest) => {
  try {
    if (formData.value.id) {
      // 更新
      await updateMenu({ ...data, id: formData.value.id })
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addMenu(data)
      ElMessage.success('添加成功')
    }
    
    // 重新获取数据
    const result = await getMenuList()
    menuData.value = result
    menuTree.value = result
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('保存菜单失败:', error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {}
  dialogVisible.value = false
}


</script>

<style scoped>
.menu-management {
  padding: 24px;
}

/* 搜索表单样式 - 美化版本 */
.search-form {
  padding: 0 24px 20px 0px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.form-item-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.form-item-inline label {
  font-size: 14px;
  font-weight: 600;
  color: #475569;
  white-space: nowrap;
  min-width: 60px;
}

.form-item-inline .el-input,
.form-item-inline .el-select {
  width: 160px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

.add-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 菜单列表容器样式 */
.menu-list-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  overflow: hidden;
  max-height: 550px;
  display: flex;
  flex-direction: column;
}

/* 列表头部样式 */
.list-header {
  display: flex;
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
  border-bottom: 1px solid #c7d2fe;
  padding: 16px 20px;
  font-weight: 600;
  color: #4338ca;
  font-size: 16px;
  position: sticky;
  top: 0;
  z-index: 10;
  min-width: max-content;
}

.header-item {
  display: flex;
  align-items: center;
}

.name-col {
  flex: 1.2;
  min-width: 150px;
}

.path-col {
  flex: 1.5;
  min-width: 180px;
}

.type-col {
  flex: 0.8;
  min-width: 80px;
}

.sort-col {
  flex: 0.6;
  min-width: 60px;
}

.status-col {
  flex: 0.8;
  min-width: 80px;
}

.action-col {
  flex: 1.5;
  min-width: 180px;
}

/* 列表滚动容器 */
.list-scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: auto;
}

.list-content {
  background: white;
}

.list-item {
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.list-item:hover {
  background: #f8fafc;
}

.list-item:last-child {
  border-bottom: none;
}

.list-row {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  min-height: 60px;
  min-width: max-content;
}

/* 菜单名称列样式 */
.name-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.name {
  font-weight: 500;
  color: #1f2937;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 6px;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .menu-management {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .form-item-inline {
    min-width: auto;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .form-item-inline label {
    min-width: auto;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0;
    flex-direction: column;
    gap: 8px;
  }

  .search-btn,
  .reset-btn,
  .add-btn {
    width: 100%;
  }

  .list-header,
  .list-row {
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 1024px) {
  .form-row {
    gap: 16px;
  }

  .form-item-inline {
    min-width: 180px;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 140px;
  }

  .button-group {
    flex-wrap: wrap;
  }
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}
</style>
